<?php

class Wxgzh{
    private $appid='';
    private $secret='';
    public function __construct($wx)
    {
        $this->appid = $wx['gzh']['appid'];
        $this->secret = $wx['gzh']['secret'];
    }


    /**
     * 用于测试
     */
    public function test($params){
        $code = $params['invite_code'];
        $site_url = "http://api.jiruanos.com/test/userinfo";
        $url_code = array();
        $url_code["appid"] = $this->appid;
        $url_code["redirect_uri"] = urlencode($site_url);
        $url_code["response_type"] = "code";
        $url_code["scope"] = "snsapi_userinfo";//snsapi_base
        $url_code["state"] = $code;
        $get_code_url = "https://open.weixin.qq.com/connect/oauth2/authorize?" . $this->ToUrlParams($url_code);
        if (!isset($params['code'])) {
            header("location:$get_code_url");
        }
    }




    /**
     * @func 以前老的需要跳转的微信app端获取code进行邀请人
     * @param $param 参数
     * @param $code
     * @return mixed
     */
    public function  getcode($params){
        if(strstr($_SERVER['HTTP_HOST'],'mayikuaizhan.com')){
            $site_url = "http://mayikuaizhan.com/invite/getaccess";
            header("location:{$site_url}");
        }
        $code = $params['invite_code'];
        $site_url = $site_url;
        $url_code = array();
        $url_code["appid"] = $this->appid;
        $url_code["redirect_uri"] = urlencode($site_url);
        $url_code["response_type"] = "code";
        $url_code["scope"] = "snsapi_userinfo";//snsapi_base
        $url_code["state"] = $code;
        $get_code_url = "https://open.weixin.qq.com/connect/oauth2/authorize?" . $this->ToUrlParams($url_code);
        if (!isset($params['code'])) {
            header("location:$get_code_url");
        }
    }




    /**
     * @func 以前老的需要跳转的微信app端获取code进行邀请人
     * @param $param 参数
     * @param $code
     * @return mixed
     */
	public function geth5token($invite_code){
		$site_url='http://mayikuaizhan.com/invite/getreturntoken';
		$code = $invite_code;
        $site_url = $site_url;
        $url_code = array();
        $url_code["appid"] = $this->appid;
        $url_code["redirect_uri"] = urlencode($site_url);
        $url_code["response_type"] = "code";
        $url_code["scope"] = "snsapi_userinfo";//snsapi_base
        $url_code["state"] = $code;
        $get_code_url = "https://open.weixin.qq.com/connect/oauth2/authorize?" . $this->ToUrlParams($url_code);
        if (!isset($params['code'])) {
            header("location:$get_code_url");
        }
    }



    /**
     * @func 微信网页端获取code进行注册
     * @param $param 参数
     * @param $code
     * @return mixed
     */
    public function  regwx($params){
        $code = $params['invite_code'];
        $site_url = "http://api.jiruanos.com/invite/regwx";
        $url_code = array();
        $url_code["appid"] = $this->appid;
        $url_code["redirect_uri"] = urlencode($site_url);
        $url_code["response_type"] = "code";
        $url_code["scope"] = "snsapi_userinfo";//snsapi_base
        $url_code["state"] = $code;
        $get_code_url = "https://open.weixin.qq.com/connect/oauth2/authorize?" . $this->ToUrlParams($url_code);
        if (!isset($params['code'])) {
            header("location:$get_code_url");
        }
    }


    /**
     * @func 获取微信网页授权的token不是基础token
     * @param $code 微信code码
     * @return mixed|string
     */
    public function gettoken($code){
        $url_openid = array();
        $url_openid["appid"] = $this->appid;
        $url_openid["secret"] = $this->secret;
        $url_openid["code"] = $code;
        $url_openid["grant_type"] = "authorization_code";
        $get_openid_url = "https://api.weixin.qq.com/sns/oauth2/access_token?" . $this->ToUrlParams($url_openid);
        $openid_info = $this->postRequest($get_openid_url, '', 'xml');
        $openid_info = json_decode($openid_info, TRUE);
        return $openid_info;
	}


	public function getjstoken($token) {
		$url='https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$token.'&type=jsapi';
		$respons = file_get_contents($url);
		$respons=json_decode($respons);
		return $respons->ticket;
	}

	public function getuserinfo($token,$openid){
        $access_token = $token;
        $openid = $openid;
        $get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
        $user_info = $this->postRequest($get_user_info_url, '', 'xml');
        $user_info = json_decode($user_info, true);
        return $user_info;
	}


	public function push_order($order,$open_id,$token){
		$template = array(
			"touser"=>$open_id,
			"template_id"=>"1qEhrvN0wnCL2YQJMdrW5UdF7Nc9zm0LvoAio0gn4_Y",
			"url"=>"www.baidu.com",
			"data"=>[
				"first"=> [
					"value"=>"收到用户的充值，请尽快充值",
					"color"=>"#173177"
				],
				"orderMoneySum"=>[
					"value"=>$order->money."元",
					"color"=>"#173177"
				],
				"orderProductName"=> [
					"value"=>"上网账号:".$order->net_nmb,
					"color"=>"#173177"
				],
				"Remark"=>[
					"value"=>"手机:".$order->mobile,
					"color"=>"#173177"
				]
			]
		);
		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $token;
		$dataRes = $this->post_request($url, $template);

	}



	public function error_report_send($params,$open_id,$token){
		$template = array(
			"touser"=>$open_id,
			"template_id"=>"gRRU8KsigAfiwmbVrFCpjZW4j6rsZ4dUZASUUV-sHNA",
			"url"=>"www.baidu.com",
			"data"=>[
				"first"=> [
					"value"=>"收到用户的故障报告，请尽快处理",
					"color"=>"#173177"
				],
				"keyword1"=>[
					"value"=>$params['name'],
					"color"=>"#173177"
				],
				"keyword2"=>[
					"value"=>date('Y-m-d H:i:s'),
					"color"=>"#173177"
				],
				"keyword3"=>[
					"value"=>$params['error_situation'],
					"color"=>"#173177"
				],
				"remark"=>[
					"value"=>'用户地址:'.$params['address'].',用户手机:'.$params['address'].',备注：'.$params['remark'],
					"color"=>"#173177"
				]
			]
		);
		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $token;
		$dataRes = $this->post_request($url, $template);
	}


	public function net_error_push($params,$open_id,$token){
	//	echo $token;die;
	//	var_dump($params);die;
		$template = array(
			"touser"=>$open_id,
			"template_id"=>"mNAH37D0BD-ZJIOeplNr5kV5BT9_G7NGceVrr8ujr8o",
			"url"=>"www.baidu.com",
			"data"=>[
				"first"=> [
					"value"=>"故障提醒",
					"color"=>"#173177"
				],
				"keyword1"=>[
					"value"=>$params['address'],
					"color"=>"#173177"
				],
				"keyword2"=>[
					"value"=>$params['error_time'],
					"color"=>"#173177"
				],
								"remark"=>[
									"value"=>$params['remark'],
					"color"=>"#173177"
				]
			]
		);
		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $token;
		$dataRes = $this->post_request($url, $template);
	}




	private function post_request($url = '', $param = '')
	{
		if (empty($url) || empty($param)) {
			return false;
		}
		$postUrl = $url;
		$curlPost = urldecode(json_encode($param));
		$ch = curl_init(); //初始化curl
		curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
		curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
		curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
		curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
		$data = curl_exec($ch); //运行curl
		curl_close($ch);
		return $data;
	}


    /**
     * 用CURL模拟提交数据
     *
     * @param string $url        post所要提交的网址
     * @param array  $data        所要提交的数据
     * @param string $proxy        代理设置
     * @param integer $expire    所用的时间限制
     * @return string
     */
    private function postRequest($url, $data = null, $type = 'array',$proxy = null, $expire = 30) {
        //参数分析
        if (!$url) {
            return false;
        }
        //cookie file
        $cookieFile = '/cache' . md5(time()) . '.txt';
        //分析是否开启SSL加密
        $ssl         = substr($url, 0, 8) == 'https://' ? true : false;
        //读取网址内容
        $ch = curl_init();
        //设置代理
        if (!is_null($proxy)) {
            curl_setopt ($ch, CURLOPT_PROXY, $proxy);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        if ($ssl) {
            // 对认证证书来源的检查
            //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            // 从证书中检查SSL加密算法是否存在
            //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
        }
        //cookie设置
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        //设置浏览器
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //发送一个常规的Post请求
        curl_setopt($ch, CURLOPT_POST, true);
        //Post提交的数据包
        if($type == 'array'){
            curl_setopt($ch,  CURLOPT_POSTFIELDS, http_build_query($data));
        }else{
            curl_setopt($ch,  CURLOPT_POSTFIELDS, $data);
        }
        //使用自动跳转
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $expire);
        $content = curl_exec($ch);
        curl_close($ch);
        return $content;
    }


    /** 参数转换
     * @param $urlObj
     * @return string
     */
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v) {
            if ($k != "sign") {
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }



}
